import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../services/api_service.dart';
import '../../utils/logger.dart';
import 'package:base_flutter/src/network/network_exception.dart';
import 'order_success_page.dart';

/// 支付页面
class PaymentPage extends StatefulWidget {
  final int orderId;
  final String orderNo;
  final double amount;

  const PaymentPage({
    super.key,
    required this.orderId,
    required this.orderNo,
    required this.amount,
  });

  @override
  State<PaymentPage> createState() => _PaymentPageState();
}

class _PaymentPageState extends State<PaymentPage> {
  bool _isPaying = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('确认支付'),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0,
      ),
      body: Column(
        children: [
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                children: [
                  // 订单金额
                  Container(
                    padding: const EdgeInsets.all(32),
                    color: Colors.white,
                    child: Column(
                      children: [
                        const Text(
                          '订单金额',
                          style: TextStyle(fontSize: 16, color: Colors.grey),
                        ),
                        const SizedBox(height: 8),
                        Text(
                          '¥${widget.amount.toStringAsFixed(2)}',
                          style: const TextStyle(
                            fontSize: 40,
                            fontWeight: FontWeight.bold,
                            color: Colors.red,
                          ),
                        ),
                        const SizedBox(height: 8),
                        Text(
                          '订单号：${widget.orderNo}',
                          style: const TextStyle(fontSize: 12, color: Colors.grey),
                        ),
                      ],
                    ),
                  ),
                  const Divider(height: 1),
                  
                  // 支付方式
                  Container(
                    padding: const EdgeInsets.all(16),
                    color: Colors.white,
                    child: const Row(
                      children: [
                        Icon(Icons.account_balance_wallet, color: Colors.blue),
                        SizedBox(width: 12),
                        Expanded(
                          child: Text(
                            '余额支付',
                            style: TextStyle(fontSize: 16),
                          ),
                        ),
                        Icon(Icons.check_circle, color: Colors.blue),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          
          // 底部支付按钮
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.grey.withOpacity(0.2),
                  spreadRadius: 1,
                  blurRadius: 3,
                  offset: const Offset(0, -1),
                ),
              ],
            ),
            child: SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: _isPaying ? null : _pay,
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue,
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                ),
                child: _isPaying
                    ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                        ),
                      )
                    : Text(
                        '确认支付 ¥${widget.amount.toStringAsFixed(2)}',
                        style: const TextStyle(
                          fontSize: 18,
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 支付
  Future<void> _pay() async {
    setState(() => _isPaying = true);

    try {
      // 调用支付接口
      final result = await ApiService().payOrder(widget.orderId);

      Logger.d('PAYMENT', '支付成功: $result');

      if (!mounted) return;

      // 跳转到支付成功页面
      final successResult = await Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => OrderSuccessPage(
            orderNo: widget.orderNo,
            amount: widget.amount,
            virtualContent: result['virtualContent'],
          ),
        ),
      );

      // 返回结果
      if (mounted) {
        Navigator.pop(context, successResult ?? {'success': true});
      }
    } catch (e) {
      Logger.e('PAYMENT', '支付失败: $e');
      
      if (!mounted) return;
      
      setState(() => _isPaying = false);
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('支付失败: ${e is NetworkException ? e.message : e.toString()}'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }
}
